/**
 * 文件名：AuthService.java
 * 功能：认证服务类，处理注册和登录的业务逻辑
 * 作用：实现用户注册、登录验证、密码加密、JWT Token 生成等核心业务逻辑
 * 模块关系：
 *   - 被 AuthController 调用：提供注册和登录服务
 *   - 依赖 UserMapper：查询和插入用户数据
 *   - 依赖 PasswordEncoder：使用 BCrypt 加密密码
 *   - 依赖 JwtTokenUtil：生成 JWT Token
 *   - 抛出 BusinessException：用户名重复、密码错误等情况
 * 作者：白永康
 * 学号：2501210209
 */
package com.example.demo.auth.service;

import com.example.demo.auth.dto.AuthResponse;
import com.example.demo.auth.dto.LoginRequest;
import com.example.demo.auth.dto.RegisterRequest;
import com.example.demo.common.BusinessException;
import com.example.demo.security.JwtTokenUtil;
import com.example.demo.user.entity.UserEntity;
import com.example.demo.user.mapper.UserMapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 认证服务类
 * 处理用户注册和登录的业务逻辑
 */
@Service
public class AuthService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtTokenUtil jwtTokenUtil;

    /**
     * 构造函数，注入依赖
     * @param userMapper 用户数据访问层
     * @param passwordEncoder 密码加密器
     * @param jwtTokenUtil JWT 工具类
     */
    public AuthService(UserMapper userMapper, 
                      PasswordEncoder passwordEncoder,
                      JwtTokenUtil jwtTokenUtil) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    /**
     * 用户注册服务
     * @param request 注册请求参数
     * @return 认证响应，包含 Token 和用户信息
     * @throws BusinessException 用户名已存在时抛出
     */
    public AuthResponse register(RegisterRequest request) {
        // 检查用户名是否已存在
        UserEntity existing = userMapper.findByUsername(request.getUsername());
        if (existing != null) {
            throw new BusinessException(400, "用户名已存在");
        }

        // 创建新用户
        UserEntity user = new UserEntity();
        user.setUsername(request.getUsername());
        user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        userMapper.insert(user);

        // 生成 JWT Token
        String token = jwtTokenUtil.generateToken(user.getId(), user.getUsername());

        return AuthResponse.builder()
                .token(token)
                .userId(user.getId())
                .username(user.getUsername())
                .build();
    }

    /**
     * 用户登录服务
     * @param request 登录请求参数
     * @return 认证响应，包含 Token 和用户信息
     * @throws BusinessException 用户名或密码错误时抛出
     */
    public AuthResponse login(LoginRequest request) {
        // 查找用户
        UserEntity user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
            throw new BusinessException(401, "用户名或密码错误");
        }

        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) {
            throw new BusinessException(401, "用户名或密码错误");
        }

        // 生成 JWT Token
        String token = jwtTokenUtil.generateToken(user.getId(), user.getUsername());

        return AuthResponse.builder()
                .token(token)
                .userId(user.getId())
                .username(user.getUsername())
                .build();
    }
}
